package com.example.sellqq.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.sellqq.constant.ResourceConstant;
import com.example.sellqq.util.FileUtils;
import com.example.sellqq.vo.ResponseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Author: thekernel
 * @Date: 2020/4/20 10:46
 * @Version: 1.0
 * @Description:
 */
@Api(value = "公告Controller")
@RestController
@RequestMapping("announcement")
public class AnnouncementController {

    @ApiIgnore
    @GetMapping("hello")
    public @ResponseBody
    String index() {
        return "Hello Announcement !!!";
    }

    @ApiOperation(value = "获取公告栏信息", notes = "公告栏信息")
    @GetMapping("/")
    public @ResponseBody
    ResponseVO getAnnouncement() {
        JSONObject returnData = (JSONObject) JSONObject.parse(FileUtils.getAnnouncement());
        return ResponseVO.success("读取公告栏成功", returnData);
    }

    @ApiOperation(value = "修改公告栏信息", notes = "公告栏信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "公告栏信息", required = true, dataTypeClass = String.class, paramType = "body"),
    })
    @PutMapping("/")
    public @ResponseBody
    ResponseVO updateAnnouncement(@RequestBody String content) throws IOException {
        JSONObject returnData = (JSONObject) JSONObject.parse(FileUtils.getAnnouncement());
        returnData.replace("content", content);
        try {
            File file = new File(ResourceConstant.ABSOLUTE_ANNOUNCEMENT_FILE_PATH);
            FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fileWriter);
            bw.write(returnData.toString());
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseVO.success("修改成功", returnData);
    }
}
